<template>
  <NavBar title="发表动态" to="/dynamic">
    <template #right>
      <var-link @click="publish" type="primary" underline="none">发表</var-link>
    </template>
  </NavBar>

  <var-input
    variant="outlined"
    placeholder="说点什么吧..."
    textarea
    v-model="content"
  />

  <var-uploader
    :maxlength="3"
    v-model="imgs"
    @remove="removeImg"
    @after-read="handleAfterReadImg"
  />
</template>

<script setup lang="ts">
import NavBar from '@/components/NavBar.vue'
import { publishDynamic, uploadDynamicPic, deleteDynamicPic } from '@/api'

const router = useRouter()

const content = ref('')
const imgs = ref([])
const imgUrls = ref([])

const handleAfterReadImg = async (file: File) => {
  const formData = new FormData()
  formData.append('file', file.file)
  const res = await uploadDynamicPic(formData)
  imgUrls.value.push({
    id: file.id,
    url: res[0]
  })
}

const removeImg = async (file: File) => {
  const item = imgUrls.value.find(item => item.id === file.id)
  await deleteDynamicPic([item.url])
  imgUrls.value = imgUrls.value.filter(item => item.id !== file.id)
}

const publish = async () => {
  const parmas = {
    content: content.value,
    img: imgUrls.value.map(item => item.url)
  }
  const res = await publishDynamic(parmas)
  Snackbar.success(res)
  router.push('/dynamic')
}
</script>

<style scoped lang="scss">
.var-input {
  margin: 10px 0;
}
</style>
